//
//  EditProductDefImgVC.m
//  AFNetworking
//
//  Created by MBA on 2020/5/1.
//

#import "EditProductDefImgVC.h"
#import "DefualCollectionViewCell.h"
#import "PageImageView.h"
#import "EditProductDefImgCell.h"
#import <TZImagePickerController/TZImagePickerController.h>

@interface EditProductDefImgVC ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UIImagePickerControllerDelegate,TZImagePickerControllerDelegate>

@property(strong,nonatomic) UIButton *navEditBtn;

@property (nonatomic, strong) PageImageView* pageImageView;
@property (nonatomic, strong) UILabel* remarkLab;
@property (nonatomic, strong) UICollectionView * collectionView;
@property (nonatomic, strong) NSMutableArray * datalist;
@property (nonatomic, strong)UICollectionViewFlowLayout * flowLayout;
/// 是否移动
@property (nonatomic, assign) BOOL isBeganMove;
@end

@implementation EditProductDefImgVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self configUI];
}

-(void)configUI{
    self.title = @"添加图片";
    [self.view addSubview:self.pageImageView];
    [self.view addSubview:self.collectionView];
    [self.view addSubview:self.remarkLab];
    
    UIBarButtonItem *buttonItem = [[UIBarButtonItem alloc]
     initWithCustomView:self.navEditBtn];
     [self.navigationItem setRightBarButtonItem:buttonItem];
}
-(UIButton *)navEditBtn{
    if (!_navEditBtn) {
        _navEditBtn = [UIButton  buttonWithType:UIButtonTypeCustom];
        [_navEditBtn setFrame:CGRectMake(0, 0, 30, 40)];
        [_navEditBtn setTitle:@"确认" forState:UIControlStateNormal];
        [_navEditBtn setTitle:@"确认" forState:UIControlStateSelected];
        [_navEditBtn setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
        [_navEditBtn addTarget:self action:@selector(rightBarButtonItemClick:) forControlEvents:UIControlEventTouchUpInside];
         [self.navEditBtn setHidden:YES];
    }
    return _navEditBtn;

}

-(void)rightBarButtonItemClick:(UIButton*)sender{
    _data.pic = [_datalist componentsJoinedByString:@","];
    [self.navigationController popViewControllerAnimated:YES];
}

-(UILabel *)remarkLab{
    if (!_remarkLab) {
        _remarkLab = [UILabel new];
        _remarkLab.textColor = COLOR_99;
        _remarkLab.font = FONT_SYS13;
        _remarkLab.text = @"长按图片可拖动排序";
    }
    return _remarkLab;
}
-(NSMutableArray *)datalist{
    if (!_datalist) {
        _datalist = [@[] mutableCopy];
    }
    return _datalist;
}
-(PageImageView *)pageImageView{
    if (!_pageImageView) {
        _pageImageView = [PageImageView new];
         _pageImageView.datalist = self.datalist;
        [_pageImageView ug_borderColor:COLOR_EE width:1];
        [_pageImageView ug_radius:8];
    }
    return _pageImageView;
}
-(UICollectionView *)collectionView{
    if (!_collectionView) {
        
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:self.flowLayout];
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        [_collectionView registerClass:[EditProductDefImgCell class] forCellWithReuseIdentifier:@"EditProductDefImgCell"];
    }
    return _collectionView;
}
-(UICollectionViewFlowLayout *)flowLayout{
    if (!_flowLayout) {
        _flowLayout = [UICollectionViewFlowLayout new];
        _flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    }
    return _flowLayout;
}

#pragma mark UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    NSInteger count = (self.datalist.count+1)<=5 ? (self.datalist.count+1) : 5;
    return count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    EditProductDefImgCell * cell = (EditProductDefImgCell*)[collectionView dequeueReusableCellWithReuseIdentifier:@"EditProductDefImgCell" forIndexPath:indexPath];

    if (indexPath.row<self.datalist.count) {
        //添加长按手势
        UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(moveCollectionViewCell:)];
        [cell addGestureRecognizer:longPress];
        cell.deleteBtn.hidden = NO;
    }else{
        [cell.imageView setImage:UGIMAGE(@"icon_sctp")];
        cell.deleteBtn.hidden = YES;
    }
    UG_WEAKSELF
    __weak typeof(indexPath) weakindex = indexPath;
    [cell.deleteBtn ug_addEvents:UIControlEventTouchUpInside andBlock:^(id  _Nonnull sender) {
        [weakSelf.datalist removeObjectAtIndex:weakindex.row];
        [self.collectionView  reloadData];
        [weakSelf.pageImageView.collectionView reloadData];
    }];
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    return CGSizeMake(KAutoAcale(58), KAutoAcale(58));
    
}
-(BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath{
    return  indexPath.row < self.datalist.count;
}
-(void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {
    
    NSString *selectModel = self.datalist[sourceIndexPath.row];
    [_datalist removeObjectAtIndex:sourceIndexPath.row];
    [_datalist insertObject:selectModel atIndex:destinationIndexPath.row];
    [_pageImageView.collectionView reloadData];
    //此处可以根据需要，上传给后台目前数据的顺序
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    [self selectImage:indexPath];
}
#pragma mark - 手势事件
-(void)moveCollectionViewCell:(UILongPressGestureRecognizer *)gesture {
    switch (gesture.state) {
        case UIGestureRecognizerStateBegan: {
            if (!self.isBeganMove) {
                self.isBeganMove = YES;
                //获取点击的cell的indexPath
                NSIndexPath *selectedIndexPath = [self.collectionView indexPathForItemAtPoint:[gesture locationInView:self.collectionView]];
                
                //开始移动对应的cell
                [self.collectionView beginInteractiveMovementForItemAtIndexPath:selectedIndexPath];
            }
            break;
        }
        case UIGestureRecognizerStateChanged: {
            //移动cell
            NSIndexPath *selectedIndexPath = [self.collectionView indexPathForItemAtPoint:[gesture locationInView:self.collectionView]];
            if (selectedIndexPath.row<_datalist.count) {
                [self.collectionView updateInteractiveMovementTargetPosition:[gesture locationInView:self.collectionView]];
            }
            
            break;
        }
        case UIGestureRecognizerStateEnded: {
            self.isBeganMove = false;
            //结束移动
            [self.collectionView endInteractiveMovement];
            break;
        }
        default:
            [self.collectionView cancelInteractiveMovement];
            break;
    }
}


-(void)selectImage:(NSIndexPath*)index{
    
    TZImagePickerController *pickerController = [[TZImagePickerController alloc]initWithMaxImagesCount:1 delegate:self];
    pickerController.statusBarStyle = UIStatusBarStyleDefault;
    __weak typeof(self) weakSelf = self;
    __weak typeof(index) weakindex = index;
    [pickerController setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photo, NSArray *assets, BOOL isSelectOriginalPhoto){
        [self.view ug_starloading];
        if (photo.count) {
            UIImage *image =  photo[0];
            DefualCollectionViewCell * cell =(DefualCollectionViewCell*) [weakSelf.collectionView cellForItemAtIndexPath:weakindex];
            [cell.imageView setImage:image];
            if (weakindex.row<weakSelf.datalist.count) {
                [weakSelf.datalist replaceObjectAtIndex:weakindex.row withObject:@"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1588768190721&di=8af06e1c7b9590a804429e06b0bfee8e&imgtype=0&src=http%3A%2F%2Ft8.baidu.com%2Fit%2Fu%3D2857883419%2C1187496708%26fm%3D79%26app%3D86%26f%3DJPEG%3Fw%3D1280%26h%3D763"];
            }else{
                 [weakSelf.datalist addObject:@"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1588768190721&di=8af06e1c7b9590a804429e06b0bfee8e&imgtype=0&src=http%3A%2F%2Ft8.baidu.com%2Fit%2Fu%3D2857883419%2C1187496708%26fm%3D79%26app%3D86%26f%3DJPEG%3Fw%3D1280%26h%3D763"];
            }
            [weakSelf.pageImageView.collectionView reloadData];
            [weakSelf.collectionView reloadData];
            
        }
        [self.view ug_stoploading];
    }];
    [self presentViewController:pickerController animated:YES completion:nil];
}

-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    [_pageImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view).mas_offset(KPAND_DEF);
        make.left.mas_equalTo(self.view).mas_offset(KPAND_DEF);
        make.right.mas_equalTo(self.view).mas_offset(-KPAND_DEF);
        make.height.mas_equalTo(KAutoAcale(355));
    }];
    [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.pageImageView.mas_bottom).mas_offset(KPAND_DEF);
        make.left.mas_equalTo(self.view).mas_offset(KPAND_DEF);
        make.right.mas_equalTo(self.view).mas_offset(-KPAND_DEF);
        make.height.mas_equalTo(90);
    }];
    [_remarkLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.collectionView.mas_bottom);
        make.left.mas_equalTo(self.collectionView);
    }];
}
@end
